package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
@Slf4j
public class MaxLoginUtils {
    //检查当前用户登录的次数，返回boolean
    @Value("${maxLoginCount}")
    private static Integer maxCount;

    @Autowired
    private static RedisTemplate redisTemplate;

    public static boolean CheckLoginCount(String username){

        // 1.判断当前用户是否已经登录
        if(redisTemplate.hasKey(username)){
            //已经登录 判断个数
            Integer loginCount = (Integer) redisTemplate.opsForValue().get(username);

            log.info("当前个数是  {}    最大限制的是  {}",loginCount,maxCount);
            if(loginCount < maxCount){

                return true;
            }
            return false;
        }else {
            System.out.println("没有人使用");
            redisTemplate.opsForValue().set(username,0);
            //没有人使用
            return true;
        }
    }
    //多一个登录
    public static void LoginUser(String username){
        if(redisTemplate.hasKey(username)){
            Integer loginCount = (Integer) redisTemplate.opsForValue().get("username");
            redisTemplate.opsForValue().set("username",loginCount+1);
        }else {
            redisTemplate.opsForValue().set("username",1);
        }
    }
    //退出登录
    public static void outUser(String username){
        if(redisTemplate.hasKey(username)){
            Integer loginCount = (Integer) redisTemplate.opsForValue().get("username");
            redisTemplate.opsForValue().set("username",loginCount-1);
        }else {
            log.info("有问题！退出不应该不存在userKey");
        }
    }
}
